import request from '@/utils/request';
import { useState, useEffect } from 'react';
import weui from 'weui.js';
import QRCode from 'qrcode';
import { NavBar, Icon } from 'antd-mobile';
import { history, useHistory, useLocation } from 'umi';
import ReactWeui from 'react-weui';
const { Dialog, ActionSheet } = ReactWeui;
import { getUserInfo, removeUserInfo } from '@/utils/auth';
import styles from './wxpay-jsapi.less';
import classNames from '@/utils/classnames';

wx.error(function (res) {
  // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
  console.log(res);
  weui.topTips('JS-SDK验证失败：' + res.errMsg);
});

// 服务号appid
// const appid = "wxd250963102d6d4e8"
const appid = 'wx2aaa46f7c294d3e9';
const redirectUrl = window.location.origin + '/mp/login';
// const redirectUrl = 'http://h5.sssplus.cn/wxpay-jsapi';
// const redirectUrl = "http://h5.liangshanhouli.cn/wxpay-jsapi"
// const redirectUrl = "http://172.16.3.16:11000/wxpay-jsapi"

enum ScopeType {
  base = 'snsapi_base',
  userinfo = 'snsapi_userinfo',
}

function build_authorize_url(
  appid: string,
  redirect_uri: string,
  scope: string,
  state: string,
) {
  if (!appid) {
    throw Error('appid 不能为空');
  }
  if (!redirect_uri) {
    throw Error('redirect_uri 不能为空');
  }
  let encodedRedirectUrl = encodeURI(redirect_uri);
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodedRedirectUrl}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
}

function get_snsapi_base_authorize_url(
  appid: string,
  redirect_uri: string,
  state: string,
) {
  return wx.authorize.getAuthorizeUrl({
    appid: appid,
    redirect_uri: redirect_uri,
    scope: ScopeType.base,
    state: state,
  });
  // return build_authorize_url(appid, redirect_uri, ScopeType.base, state);
}

function get_snsapi_userinfo_authorize_url(
  appid: string,
  redirect_uri: string,
  state: string,
) {
  return wx.authorize.getAuthorizeUrl({
    appid: appid,
    redirect_uri: redirect_uri,
    scope: ScopeType.userinfo,
    state: state,
  });
  // return build_authorize_url(appid, redirect_uri, ScopeType.userinfo, state);
}

export default function WxpayJSAPIPage() {
  const [amount, setAmount] = useState('0.01');
  const [dialogStyle, setDialogStyle] = useState({ display: 'none' });
  const [qrcode, setQrcode] = useState('');
  const [showDialog, setShowDialog] = useState(false);
  // 公众号授权code
  const [code, setCode] = useState('');
  const [userInfo, setUserInfo] = useState(getUserInfo());
  const [actionSheetOptions, setActionSheetOptions] = useState({
    show: false,
    menus: [
      {
        label: 'snsapi_base',
        onClick: () => {
          setActionSheetOptions({ ...actionSheetOptions, show: false });
          window.location.href = get_snsapi_base_authorize_url(
            appid,
            redirectUrl,
            '',
          );
        },
      },
      {
        label: 'snsapi_userinfo',
        onClick: () => {
          setActionSheetOptions({ ...actionSheetOptions, show: false });
          window.location.href = get_snsapi_userinfo_authorize_url(
            appid,
            redirectUrl,
            '',
          );
        },
      },
    ],
  });
  const dialogButtons = [
    {
      type: 'default',
      label: '知道了',
      onClick: () => setShowDialog(false),
    },
  ];

  // const history = useHistory();
  // console.log(history);
  const location = useLocation();
  console.log(location);

  useEffect(() => {
    // wx.checkJsApi({
    //   jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
    //   success: function (res) {
    //     // 以键值对的形式返回，可用的api值true，不可用为false
    //     // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
    //     console.log(res);
    //     if (res.checkResult.chooseWXPay) {
    //       jsapiConfig()
    //     }
    //   },
    // });
  }, []);

  function jsapiConfig() {
    var loading = weui.loading('请求js-sdk权限签名...');
    request('/api/jsapi/js-sdk/sign', {
      method: 'POST',
      data: {
        url: window.location.href,
      },
      requestType: 'form',
    })
      .then((res) => {
        console.log(res);
        const { data } = res;

        wx.config({
          // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appId, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名
          jsApiList: ['chooseWXPay', 'wx-open-subscribe'], // 必填，需要使用的JS接口列表
          openTagList: ['wx-open-subscribe'], // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
        });
        // weui.toast('请求js-sdk权限签名成功', 2000);
      })
      .finally(() => {
        loading.hide();
      });
  }

  function navBarGoBack() {
    history.goBack();
  }

  function handleAuthorize() {
    var loading = weui.loading('获取授权...');
    window.location.href = get_snsapi_base_authorize_url(
      appid,
      redirectUrl,
      '',
    );
  }

  function handleLogout() {
    weui.confirm(
      '是否确认退出登录？',
      function () {
        console.log('yes');
        removeUserInfo();
        setUserInfo(null);
      },
      function () {
        console.log('no');
      },
    );
  }

  function handleSubmit() {
    var loading = weui.loading('提交中...');
    request('/api/unifiedorder/jsapi', {
      method: 'POST',
      data: {
        amount,
        openid: userInfo.openid,
      },
      requestType: 'form',
    })
      .then((res) => {
        console.log(res);
        const { data } = res;
        handleChooseWxpay(data);
      })
      .finally(() => {
        loading.hide();
      });
  }

  function handleChooseWxpay(data: any) {
    // alert(wx.chooseWXPay)
    // var resData = data || {
    //     "paySign": "0ECD04E086D7019CC4A1B14EE0EDE95933D1B77DA09EFE0C437ABF1D76CE9E46",
    //     "signType": "HMAC-SHA256",
    //     "nonceStr": "863syq2b1su6wm9s6th0jiogw3uprjn3",
    //     "timeStamp": "1635927556",
    //     "package": "prepay_id=wx031605140194411205228af865f0cb0000",
    //     "prepay_id": "wx031605140194411205228af865f0cb0000"
    // }
    var resData = data;
    wx.chooseWXPay({
      timestamp: resData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
      nonceStr: resData.nonceStr, // 支付签名随机串，不长于 32 位
      package: resData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
      signType: resData.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
      paySign: resData.paySign, // 支付签名
      success: function (res) {
        // 支付成功后的回调函数
        console.log(res);
      },
    });
  }

  return (
    <div className="page">
      <div className="page__navbar">
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          leftContent="返回"
          onLeftClick={() => navBarGoBack()}
          // rightContent={[
          //     <Icon key="0" type="search" style={{ marginRight: '16px' }} />,
          //     <Icon key="1" type="ellipsis" />,
          // ]}
        >
          {/* JSAPI支付 */}
        </NavBar>
      </div>
      <div className="weui-form">
        <div className="weui-form__text-area">
          <h2 className="weui-form__title">JSAPI支付</h2>
        </div>

        <wx-open-subscribe
          template="TenvU22BA1jCp4YHfYEpRuESXYReQyDuhs4vbdWA99I"
          id="subscribe-btn"
        >
          <script type="text/wxtag-template" slot="style">
            <style></style>
          </script>
          <script type="text/wxtag-template">
            <button
              className={classNames(
                'subscribe-btn weui-btn weui-btn__primary',
                styles['wx-open-subscribe-tag'],
              )}
            >
              一次性模版消息订阅
            </button>
          </script>
        </wx-open-subscribe>
        <div className="weui-form__text-area">
          {userInfo ? (
            // <span>已登录</span>
            <button
              className="weui-btn weui-btn_default"
              onClick={() => handleLogout()}
            >
              退出登录
            </button>
          ) : (
            <button
              className="weui-btn weui-btn_primary"
              onClick={() =>
                setActionSheetOptions({ ...actionSheetOptions, show: true })
              }
            >
              登录
            </button>
          )}
        </div>
        <div className="weui-form__control-area">
          <div className="weui-cells__group weui-cells__group_form">
            <div className="weui-cells weui-cells_form">
              <label htmlFor="js_input1" className="weui-cell weui-cell_active">
                <div className="weui-cell__hd">
                  <span className="weui-label">金额</span>
                </div>
                <div className="weui-cell__bd">
                  <input
                    name="amount"
                    id="js_input1"
                    className="weui-input"
                    placeholder="填写金额"
                    onChange={(e) => setAmount(e.target.value)}
                    value={amount}
                  />
                </div>
              </label>
            </div>
            <div className="weui-cells weui-cells_form">
              <label htmlFor="js_input1" className="weui-cell weui-cell_active">
                <div className="weui-cell__hd">
                  <span className="weui-label">code</span>
                </div>
                <div className="weui-cell__bd">
                  {code}
                  {/* <input
                                        name="amount"
                                        id="js_input1"
                                        className="weui-input"
                                        placeholder="填写金额"
                                        onChange={(e) => setAmount(e.target.value)}
                                        value={amount}
                                    /> */}
                </div>
              </label>
            </div>
          </div>
        </div>
        <div className="weui-form__opr-area">
          <button
            type="button"
            role="button"
            className={`weui-btn weui-btn_primary`}
            onClick={() => jsapiConfig()}
          >
            验证支付接口
          </button>
          <button
            type="button"
            role="button"
            disabled={amount ? false : true}
            aria-disabled="true"
            className={`weui-btn weui-btn_primary ${
              amount ? '' : 'weui-btn_disabled'
            }`}
            id="showTooltips"
            onClick={() => handleSubmit()}
          >
            下单
          </button>
          {/* <button
            className="weui-btn weui-btn__default"
            onClick={() => handleChooseWxpay()}
          >
            支付
          </button> */}
        </div>
        <div className="weui-form__extra-area">
          <div className="weui-footer">
            <p className="weui-footer__links">
              <a
                className="weui-footer__link"
                onClick={() => history.push('/wxpay-jsapi-demo')}
              >
                Demo
              </a>
            </p>
            <p className="weui-footer__text">Copyright © 2008-2019 weui.io</p>
          </div>
        </div>
      </div>
      <div
        className="js_dialog"
        role="dialog"
        aria-hidden="true"
        aria-modal="true"
        aria-labelledby="js_title2"
        id="iosDialog2"
        style={dialogStyle}
      >
        <div className="weui-mask"></div>
        <div className="weui-dialog">
          <div className="weui-dialog__hd">
            <strong className="weui-dialog__title" id="js_title3">
              使用微信扫一扫支付
            </strong>
          </div>
          <div className="weui-dialog__bd">
            {/* <QRCode value={qrcode} size={256} className="img-thumbnail" /> */}
            <img src={qrcode} className="img-thumbnail"></img>
          </div>
          <div className="weui-dialog__ft">
            <a
              role="button"
              className="weui-dialog__btn weui-dialog__btn_primary"
              onClick={() => setDialogStyle({ display: 'none' })}
            >
              知道了
            </a>
          </div>
        </div>
      </div>
      <Dialog
        title="使用微信扫一扫支付"
        show={showDialog}
        buttons={dialogButtons}
      >
        <img src={qrcode} className="img-thumbnail"></img>
      </Dialog>
      <ActionSheet
        show={actionSheetOptions.show}
        menus={actionSheetOptions.menus}
        type="android"
      ></ActionSheet>
    </div>
  );
}
